<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
      <el-form-item>
        <el-input
          v-model="queryParams.bom_code"
          placeholder="请输入BOM编号"
          clearable
          size="small"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item>
        <el-input
        v-model="queryParams.product_name"
        placeholder="请输入产品名称"
        clearable
        size="small"
        style="width: 240px"
      />
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="queryParams.bom_version"
          placeholder="请输入BOM版本号"
          clearable
          size="small"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button plain @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 标题和操作按钮 -->
    <div class="title-container">
      <h4 class="title"></h4>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDeletes">批量删除</el-button>
      </el-col>
    </el-row>

    <!-- BOM列表 -->
    <el-table
      v-loading="loading"
      :data="bomList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="index" width="60">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
        <el-table-column label="BOM编号" align="center" prop="bom_code">
    <template slot-scope="scope">
      <span class="link-type" @click="handleView(scope.row)">{{ scope.row.bom_code || '' }}</span>
    </template>
  </el-table-column>
      <el-table-column label="版本号" align="center" prop="bom_version" width="100" />
      <el-table-column label="产品名称" align="center" prop="product_name" :show-overflow-tooltip="true" />
      <el-table-column label="产品编号" align="center" prop="product_code" width="120" />
      <el-table-column label="规格型号" align="center" prop="product_sfn" width="120" />
      <el-table-column label="单位" align="center" prop="product_unit" width="80" />
      <el-table-column label="默认BOM" align="center" prop="bom_status" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.bom_status == 1 ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="日产量" align="center" prop="bom_output" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" class="blue-text">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" class="red-text">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- BOM表单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <!-- 标签页导航 -->
      <el-tabs v-model="activeTab">
        <!-- 基础信息标签页 -->
        <el-tab-pane label="基础信息" name="basic">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="BOM编号" prop="bomCode" required>
                  <el-input v-model="form.bomCode" placeholder="点击右侧按钮获取编号" :disabled="true" class="bom-code-input">
                    <el-button v-if="!form.id" slot="append" icon="el-icon-refresh" @click="handleGetAutoNumber" title="获取自动编号">获取编号</el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="默认BOM" prop="isDefault" required>
                  <el-radio-group v-model="form.isDefault">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="BOM版本" prop="bomVersion">
                  <el-input v-model="form.bomVersion" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品名称" prop="productName" required>
                  <el-input v-model="form.productName" placeholder="请选择产品">
                    <el-button slot="append" icon="el-icon-more" @click="openProductSelector"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="产品编号" prop="productCode">
                  <el-input v-model="form.productCode" placeholder="请输入" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="规格型号" prop="productSpec">
                  <el-input v-model="form.productSpec" placeholder="请输入" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="单位" prop="unit">
                  <el-input v-model="form.unit" placeholder="请输入" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="日产量" prop="dailyCapacity">
                  <el-input-number v-model="form.dailyCapacity" :min="0" :precision="0" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" type="textarea" placeholder="请输入" rows="3" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 物料配件标签页 -->
        <el-tab-pane label="物料配件" name="materials">
          <div class="material-container">
            <div class="material-header">
              <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddMaterial">添加</el-button>
              <el-button size="small" icon="el-icon-delete" @click="handleBatchRemoveMaterial" :disabled="materialIds.length === 0">移除</el-button>
            </div>
            <!-- 物料表格 -->
            <el-table
              v-loading="materialLoading"
              :data="materialList"
              border
              @selection-change="handleMaterialSelectionChange"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="序号" align="center" width="60">
                <template slot-scope="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column label="物料名称" align="center" prop="material_name" :show-overflow-tooltip="true" />
              <el-table-column label="物料编号" align="center" prop="material_code" width="120" />
              <el-table-column label="规格型号" align="center" prop="material_sfn" width="120" />
              <el-table-column label="单位" align="center" prop="unit" width="80" />
              <el-table-column label="操作" align="center" width="100">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRemoveMaterial(scope.row)" class="red-text">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="empty-data" v-if="materialList.length === 0">
              <div class="empty-icon">
                <i class="el-icon-document"></i>
              </div>
              <div class="empty-text">暂无数据</div>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 工艺路线标签页 -->
        <el-tab-pane label="工艺路线" name="process">
          <div class="process-container">
            <div class="empty-process" v-if="processList.length === 0">
              <div class="empty-icon">
                <i class="el-icon-document"></i>
              </div>
              <div class="empty-text">未设置工艺路线</div>
              <el-button type="primary" @click="openOperationalSelector">添加工艺路线</el-button>
            </div>
            <div class="process-list" v-else>
              <div class="process-header">
                <el-button type="primary" icon="el-icon-plus" @click="openOperationalSelector">添加工艺路线</el-button>
              </div>
                            <!-- 工艺路线表格 -->
              <el-table
                v-loading="processLoading"
                :data="processList"
                border
              >
                <el-table-column label="序号" align="center" width="60">
                  <template slot-scope="scope">
                    {{ scope.$index + 1 }}
                  </template>
                </el-table-column>
                <el-table-column label="工艺路线名称" align="center" prop="process_name" />
                <el-table-column label="工艺路线编号" align="center" prop="operational_code" width="180" />
                <el-table-column label="工艺路线说明" align="center" prop="operational_description" :show-overflow-tooltip="true" />
                <el-table-column label="操作" align="center" width="100">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRemoveProcess(scope.row)" class="red-text">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelForm">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 旧的产品/物料选择对话框已经被分成两个单独的对话框，此处已移除 -->

    <!-- 产品选择对话框 -->
    <el-dialog title="选择产品" :visible.sync="productSelectVisible" width="800px" append-to-body>
      <el-form :model="productQuery" ref="productQueryForm" :inline="true">
        <el-form-item label="产品名称">
          <el-input v-model="productQuery.product_name" placeholder="请输入产品名称" clearable size="small" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="searchProducts">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetProductQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="productSelectLoading"
        :data="productSelectList"
        border
        @row-click="handleProductRowClick"
        highlight-current-row
      >
        <el-table-column type="radio" width="55" align="center" />
        <el-table-column label="产品名称" align="center" prop="product_name" :show-overflow-tooltip="true" />
        <el-table-column label="产品编号" align="center" prop="product_code" width="120" />
        <el-table-column label="规格型号" align="center" prop="product_sfn" width="120" />
        <el-table-column label="单位" align="center" prop="product_unit" width="80" />
      </el-table>
      <pagination
        v-show="productSelectTotal > 0"
        :total="productSelectTotal"
        :page.sync="productQuery.pageNum"
        :limit.sync="productQuery.pageSize"
        @pagination="getProductList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="productSelectVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelectProduct">确定</el-button>
      </div>
    </el-dialog>
    
    <!-- 物料选择对话框 -->
    <el-dialog title="选择物料" :visible.sync="materialSelectVisible" width="800px" append-to-body>
      <el-form :model="materialQuery" ref="materialQueryForm" :inline="true">
        <el-form-item label="物料名称">
          <el-input v-model="materialQuery.product_name" placeholder="请输入物料名称" clearable size="small" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="searchMaterials">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetMaterialQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="materialSelectLoading"
        :data="materialSelectList"
        border
        @selection-change="handleMaterialSelectChange"
        highlight-current-row
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="物料名称" align="center" prop="product_name" :show-overflow-tooltip="true" />
        <el-table-column label="物料编号" align="center" prop="product_code" width="120" />
        <el-table-column label="规格型号" align="center" prop="product_sfn" width="120" />
        <el-table-column label="单位" align="center" prop="product_unit" width="80" />
      </el-table>
      <pagination
        v-show="materialSelectTotal > 0"
        :total="materialSelectTotal"
        :page.sync="materialQuery.pageNum"
        :limit.sync="materialQuery.pageSize"
        @pagination="getMaterialComponentList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="materialSelectVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelectMaterial">添加选中物料</el-button>
      </div>
    </el-dialog>
    
    <!-- 添加工艺路线对话框 -->
    <el-dialog title="添加工艺路线" :visible.sync="processDialogVisible" width="600px" append-to-body>
      <el-form :model="processForm" ref="processForm" :rules="processRules" label-width="100px">
        <el-form-item label="工序名称" prop="process_name">
          <el-input v-model="processForm.process_name" placeholder="请输入工序名称" />
        </el-form-item>
        <el-form-item label="工序描述" prop="process_desc">
          <el-input v-model="processForm.process_desc" type="textarea" placeholder="请输入工序描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProcessForm">确定</el-button>
      </div>
    </el-dialog>
    
    <!-- 工艺路线选择对话框 -->
    <el-dialog title="选择工艺路线" :visible.sync="operationalSelectVisible" width="800px" append-to-body>
      <el-form :model="operationalQuery" ref="operationalQueryForm" :inline="true">
        <el-form-item label="工艺路线名称">
          <el-input v-model="operationalQuery.operational_name" placeholder="请输入工艺路线名称" clearable size="small" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="searchOperational">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetOperationalQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="operationalSelectLoading"
        :data="operationalSelectList"
        border
        @row-click="handleOperationalRowClick"
        highlight-current-row
      >
        <el-table-column type="radio" width="55" align="center" />
        <el-table-column label="序号" align="center" width="60">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="工艺路线名称" align="center" prop="operational_name" :show-overflow-tooltip="true" />
        <el-table-column label="工艺路线编号" align="center" prop="operational_code" width="120" />
        <el-table-column label="工艺路线说明" align="center" prop="operational_description" width="200" :show-overflow-tooltip="true" />
      </el-table>
      <pagination
        v-show="operationalSelectTotal > 0"
        :total="operationalSelectTotal"
        :page.sync="operationalQuery.pageNum"
        :limit.sync="operationalQuery.pageSize"
        @pagination="getOperationalList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="operationalSelectVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelectOperational">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBom, addBom, updateBom, delBom, getBomDetail, delBomBatch} from "@/api/basic/bom";
import { listUnit } from "@/api/basic/unit";
import { listMaterial as listMaterials } from "@/api/basic/material";
import { listOperational } from "@/api/basic/operational";
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers";
import { listProducts, listProducts1 } from "@/api/basic/product";

export default {
  name: "BomManagement",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // BOM表格数据
      bomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前活动标签
      activeTab: 'basic',
      
      // 单位选项
      unitOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bom_code: undefined,
        productInfo: undefined,
        bom_version: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        bomCode: [
          { required: true, message: "请点击刷新按钮获取BOM编号", trigger: "blur" }
        ],
        bomVersion: [
          { required: true, message: "版本号不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        productCode: [
          { required: true, message: "产品编号不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "change" }
        ]
      },
      
      // 产品相关数据
      materialLoading: false,
      materialList: [],
      materialIds: [],
      materialSelectVisible: false,
      materialSelectLoading: false,
      materialSelectList: [],
      materialSelectTotal: 0,
      selectedProduct: null, // 当前选中的产品
      selectedMaterials: [], // 当前选中的物料列表（多选）
      materialQuery: {
        pageNum: 1,
        pageSize: 10,
        product_name: undefined,
        product_code: undefined
      },
      selectorType: 'product', // 记录当前选择器的用途
      
      // 工艺路线相关数据
      processLoading: false,
      processList: [],
      processDialogVisible: false,
      processForm: {
        process_id: undefined,
        process_name: undefined,
        process_desc: undefined
      },
      processRules: {
        process_name: [
          { required: true, message: "工序名称不能为空", trigger: "blur" }
        ]
      },
      editingProcessIndex: -1,
      
      // 工艺路线选择相关数据
      operationalSelectVisible: false,
      operationalSelectLoading: false,
      operationalSelectList: [],
      operationalSelectTotal: 0,
      selectedOperational: null,
      operationalQuery: {
        pageNum: 1,
        pageSize: 10,
        operational_name: undefined,
        operational_code: undefined
      },

      // 产品选择相关数据
      productSelectVisible: false,
      productSelectLoading: false,
      productSelectList: [],
      productSelectTotal: 0,
      productQuery: {
        pageNum: 1,
        pageSize: 10,
        product_name: undefined,
        product_code: undefined
      }
    };
  },
  created() {
    // 确保queryParams初始化正确，防止undefined错误
    if (!this.queryParams) {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        bom_code: '',
        product_name: '',
        bom_version: ''
      };
    }
    this.getList();
    this.getUnitOptions();
  },
  methods: {
    /** 查询BOM列表 */
    getList() {
      this.loading = true;
      // 确保查询参数中包含分页信息
      const query = {
        pageNum: this.queryParams.pageNum || 1,
        pageSize: this.queryParams.pageSize || 10,
        bom_code: this.queryParams.bom_code,
        product_name: this.queryParams.product_name,
        bom_version: this.queryParams.bom_version
      };
      
      listBom(query).then(response => {
        if (response && response.rows) {
          this.bomList = response.rows;
          this.total = response.total;
        } else {
          this.bomList = [];
          this.total = 0;
          console.warn("获取BOM列表返回数据格式异常", response);
        }
        this.loading = false;
      }).catch(error => {
        console.error("获取BOM列表失败", error);
        this.loading = false;
        this.bomList = [];
        this.total = 0;
      });
    },
    /** 获取单位选项 */
    getUnitOptions() {
      // 传递正确的分页参数
      listUnit({
        pageNum: 1,
        pageSize: 100
      }).then(response => {
        if (response && response.rows && Array.isArray(response.rows)) {
          this.unitOptions = response.rows.map(item => {
            return { label: item.unit_name, value: item.unit_name };
          });
        } else {
          console.warn("获取单位选项返回数据格式异常", response);
          this.unitOptions = [];
        }
      }).catch(error => {
        console.error("获取单位选项失败", error);
        this.unitOptions = [];
      });
    },
    //批量删除
    handleDeletes() {
    this.$modal.confirm('确认要删除选中的BOM吗？').then(() => {
      if (this.ids.length === 0) {
        this.$modal.msgError('请选择要删除的BOM');
        return;
      }
      delBomBatch(this.ids).then(response => {
        this.$modal.msgSuccess('删除成功');
        this.getList();
        this.ids = [];
      }).catch(error => {
        this.$modal.msgError('删除失败: ' + error.msg);
      });
    });
  },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        product_name: undefined,
        bom_version: undefined,
        bom_code: undefined
      };
      this.handleQuery();
    },
    /** 选择条数 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.bom_id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加BOM";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.bom_id || this.ids[0];
      this.$modal.loading("正在加载BOM数据...");
      
      // 正确定义查询参数对象
      const query = { bom_id: id };
      
      // 使用Promise.all同时获取基本信息和明细信息
      Promise.all([
        listBom(query),
        getBomDetail(id)
      ]).then(([bomResponse, detailResponse]) => {
        this.$modal.closeLoading();
        
        // 从listBom返回数据中提取第一条记录作为当前BOM数据
        if (bomResponse && bomResponse.rows && bomResponse.rows.length > 0) {
          const bomData = bomResponse.rows[0];
          console.log("获取到BOM基础数据:", bomData);
          
          // 设置基础表单数据，确保ID正确传递
          this.form = {
            id: id, // 直接使用传入的ID，而不是从bomData中获取
            bomCode: bomData.bom_code,
            bomVersion: bomData.bom_version,
            productName: bomData.product_name,
            productCode: bomData.product_code,
            productSpec: bomData.product_sfn,
            unit: bomData.product_unit,
            isDefault: parseInt(bomData.bom_status || '0'),
            dailyCapacity: bomData.bom_output,
            remarks: bomData.remarks
          };
          
          console.log("设置BOM ID:", this.form.id, "原始bom_id:", id);
          
          // 处理BOM明细信息
          console.log("BOM明细数据:", detailResponse);
          
          if (detailResponse && detailResponse.rows && Array.isArray(detailResponse.rows)) {
            // API返回的数据是数组格式，直接处理
            const detailsArray = detailResponse.rows;
            console.log("BOM明细详细数据:", JSON.stringify(detailsArray));
            
            // 从图片中看到，detailsArray中可能包含完整的工艺路线信息
            // 创建一个Map来存储唯一的工艺路线
            const operationalMap = new Map();
            
            // 根据图片分析，看看是否是包含大量字段的行数据
            if (detailsArray.length > 0) {
              const firstItem = detailsArray[0];
              console.log("首条明细数据类型:", typeof firstItem, "长度:", Array.isArray(firstItem) ? firstItem.length : Object.keys(firstItem).length);
              
              // 如果是大数组，可能是包含多个字段的行数据
              if (Array.isArray(firstItem) && firstItem.length > 20) {
                console.log("检测到行数据格式，尝试直接从特定位置获取工艺路线信息");
                
                // 在图片中，工艺路线信息位于特定位置：编号(52), 名称(51), 说明(54)
                const processRoutes = new Set(); // 用于跟踪已处理的工艺路线
                
                detailsArray.forEach(row => {
                  if (Array.isArray(row) && row.length > 54) {
                    // 定位工艺路线信息的位置
                    // 从图片看，GYLX开头的编号可能在位置52左右
                    let codePos = -1;
                    for (let i = 50; i < 55; i++) {
                      if (typeof row[i] === 'string' && row[i].startsWith('GYLX')) {
                        codePos = i;
                        break;
                      }
                    }
                    
                    if (codePos !== -1) {
                      const operationalCode = row[codePos];
                      const operationalName = row[codePos + 1]; // 名称紧跟在编号后面
                      const operationalDesc = row[codePos + 3]; // 根据图片，说明在位置54左右
                      
                      // 提取ID
                      const operationalId = operationalCode.replace('GYLX', '');
                      
                      if (!processRoutes.has(operationalCode)) {
                        processRoutes.add(operationalCode);
                        
                        operationalMap.set(operationalId, {
                          operational_id: operationalId,
                          process_name: operationalName || `工艺路线${operationalId}`,
                          operational_code: operationalCode,
                          operational_description: operationalDesc || '',
                          sequence: 1,
                          is_key_process: 0
                        });
                        
                        console.log("从行数据的固定位置提取工艺路线:", {
                          id: operationalId,
                          name: operationalName,
                          code: operationalCode,
                          desc: operationalDesc
                        });
                      }
                    }
                  }
                });
                
                // 如果从固定位置找到了工艺路线，则直接使用
                if (processRoutes.size > 0) {
                  console.log(`从固定位置成功提取了 ${processRoutes.size} 条工艺路线信息`);
                  this.processList = Array.from(operationalMap.values());
                  
                  // 处理物料信息
                  // 分离物料和工艺路线数据
                  const materials = detailsArray.filter(item => item.material_id);
                  
                  // 设置物料列表
                  this.materialList = materials.map(item => ({
                    material_id: item.material_id,
                    material_name: item.material_name || '',
                    material_code: item.material_code || '',
                    material_sfn: item.material_sfn || '',
                    unit: item.material_unit || '',
                    quantity: item.material_usage || 1,
                    is_key_material: item.is_key_material || 0
                  }));
                  
                  this.open = true;
                  this.title = "编辑BOM";
                  return;
                }
              }
            }
            
            // 检查是否是数组形式的数据
            const isArrayFormat = detailsArray.length > 0 && Array.isArray(detailsArray[0]);
            
            // 打印完整的行数据，方便分析
            console.log("行数据样例:", detailsArray.slice(0, 2));
            
            // 根据图片显示，可能是行数据格式，需要特殊处理
            // 图片显示: GYLX20250701003, 不锈钢表面处理工艺, 1, 专用于不锈钢表面抛光和处理的工艺流程，含电解抛光工序
            // 这几个值在数组中的索引位置似乎是连续的
            const rowDataProcessing = (row) => {
              try {
                // 先将行数据转换为字符串，以便分析
                const rowString = JSON.stringify(row);
                
                // 尝试匹配GYLX开头的编号
                const gylxMatch = rowString.match(/GYLX[0-9]+/);
                if (gylxMatch) {
                  const operationalCode = gylxMatch[0];
                  console.log("找到工艺路线编号:", operationalCode);
                  
                  // 提取工艺路线ID
                  const operationalId = operationalCode.replace("GYLX", "");
                  
                  // 从图片看，工艺路线名称在编号后面，工艺说明在更后面
                  let operationalName = null;
                  let operationalDesc = null;
                  
                  // 尝试从行数据中查找这些值
                  if (Array.isArray(row)) {
                    // 数组形式，尝试从相对位置找到相应的值
                    for (let i = 0; i < row.length; i++) {
                      if (row[i] === operationalCode) {
                        // 根据图片，编号后面是名称，再后面有说明
                        operationalName = row[i+1];
                        // 继续向后查找可能的描述
                        for (let j = i+2; j < row.length && j < i+10; j++) {
                          if (typeof row[j] === 'string' && row[j].includes('工艺流程')) {
                            operationalDesc = row[j];
                            break;
                          }
                        }
                        break;
                      }
                    }
                  } else if (typeof row === 'object') {
                    // 对象形式，遍历找到可能的值
                    Object.values(row).forEach(value => {
                      if (typeof value === 'string') {
                        // 查找可能的工艺路线名称
                        if (!operationalName && value.includes('处理工艺')) {
                          operationalName = value;
                        }
                        
                        // 查找可能的工艺说明（一般较长且包含"工艺流程"）
                        if (value.includes('工艺流程') && value.length > 15) {
                          operationalDesc = value;
                        }
                      }
                    });
                  }
                  
                  // 如果找到了编号和至少一个其他信息，添加到Map中
                  if (operationalId && (operationalName || operationalDesc)) {
                    operationalMap.set(operationalId, {
                      operational_id: operationalId,
                      process_name: operationalName || `工艺路线${operationalId}`,
                      operational_code: operationalCode,
                      operational_description: operationalDesc || '',
                      sequence: 1,
                      is_key_process: 0
                    });
                    console.log("从行数据添加工艺路线:", {
                      id: operationalId,
                      name: operationalName,
                      code: operationalCode,
                      desc: operationalDesc
                    });
                    return true;
                  }
                }
                
                // 从图片中发现，工艺说明可能单独存在于一个字符串中
                if (typeof row === 'string' && row.includes('工艺流程') && row.length > 15) {
                  // 可能是一个工艺说明，尝试匹配到已有的工艺路线
                  for (const [id, op] of operationalMap.entries()) {
                    if (!op.operational_description || op.operational_description === '') {
                      op.operational_description = row;
                      console.log(`为工艺路线 ${id} 添加说明:`, row);
                      return true;
                    }
                  }
                }
                
                return false;
              } catch (error) {
                console.error("处理行数据时出错:", error);
                return false;
              }
            };
            
            // 首先尝试从行数据中解析
            let processedRows = 0;
            detailsArray.forEach(item => {
              if (rowDataProcessing(item)) {
                processedRows++;
              }
            });
            
            console.log(`从行数据中成功处理了 ${processedRows} 条工艺路线记录`);
            
            // 如果行数据处理不成功，再尝试常规方法
            if (processedRows === 0) {
              // 遍历明细数据，提取工艺路线信息
              detailsArray.forEach(item => {
                let operationalId, operationalName, operationalCode, operationalDesc;
                
                // 判断是否为数组格式的数据返回
                if (isArrayFormat) {
                  // 根据图片中的索引位置提取数据
                  operationalId = item[52]; // 假设operational_id位于索引52
                  operationalName = item[51]; // 假设operational_name位于索引51
                  operationalCode = item[52]; // 假设operational_code位于索引52
                  operationalDesc = item[54]; // 假设description位于索引54
                } else if (typeof item === 'object') {
                  // 对象格式的数据
                  operationalId = item.operational_id;
                  operationalName = item.operational_name || item.process_name;
                  operationalCode = item.operational_code;
                  operationalDesc = item.operational_description || item.process_desc;
                  
                  // 检查更多可能的字段名，根据图片显示的数据结构
                  if (!operationalDesc && item.remarks) operationalDesc = item.remarks;
                  if (!operationalDesc && item.description) operationalDesc = item.description;
                  
                  // 尝试在对象的所有字段中查找可能的描述
                  if (!operationalDesc) {
                    for (const key in item) {
                      if (typeof item[key] === 'string' && 
                          item[key].includes('工艺流程') && 
                          item[key].length > 10) {
                        operationalDesc = item[key];
                        break;
                      }
                    }
                  }
                }
                
                // 检查我们是否找到了有效的工艺路线ID
                if (operationalId) {
                  // 确保不重复添加同一工艺路线
                  if (!operationalMap.has(operationalId)) {
                    operationalMap.set(operationalId, {
                      operational_id: operationalId,
                      process_name: operationalName || `工艺路线${operationalId}`,
                      operational_code: operationalCode || `GYLX${operationalId}`,
                      operational_description: operationalDesc || '',
                      sequence: item.position || 1,
                      is_key_process: item.is_key_process || 0
                    });
                    
                    console.log(`已提取工艺路线: ID=${operationalId}, 名称=${operationalName}, 编号=${operationalCode}, 说明=${operationalDesc}`);
                  }
                }
              });
            }
            
            this.processList = Array.from(operationalMap.values());
            console.log("提取的工艺路线列表:", this.processList);
            
            // 如果processList为空，尝试进一步解析数据中可能包含的工艺路线信息
            if (this.processList.length === 0) {
              // 从图片可以看到，数据可能是一个字符串记录，包含工艺路线信息
              // 尝试从各种可能的字段中提取工艺路线信息
              detailsArray.forEach(item => {
                // 检查是否有任何字段包含"工艺路线"或"GYLX"字样
                Object.entries(item).forEach(([key, value]) => {
                  if (typeof value === 'string' && 
                     (value.includes('工艺路线') || value.includes('GYLX'))) {
                    console.log(`在字段 ${key} 中找到可能的工艺路线信息: ${value}`);
                    
                    // 尝试从内容中提取ID、名称和编号
                    let opId, opName, opCode;
                    
                    // 如果包含GYLX，可能是编号
                    if (value.includes('GYLX')) {
                      const codeMatch = value.match(/GYLX[0-9]+/);
                      if (codeMatch) {
                        opCode = codeMatch[0];
                        opId = parseInt(opCode.replace('GYLX', ''));
                      }
                    }
                    
                    // 提取名称
                    if (value.includes('工艺路线')) {
                      opName = value;
                    }
                    
                    if (opId && !operationalMap.has(opId)) {
                      operationalMap.set(opId, {
                        operational_id: opId,
                        process_name: opName || `工艺路线${opId}`,
                        operational_code: opCode || `GYLX${opId}`,
                        operational_description: '',
                        sequence: 1,
                        is_key_process: 0
                      });
                    }
                  }
                });
              });
              
              this.processList = Array.from(operationalMap.values());
            }
            
            // 如果processList仍然为空但有operational_id字段，通过API获取工艺路线详情
            if (this.processList.length === 0) {
              // 收集所有不重复的工艺路线ID
              const operationalIds = new Set();
              
              detailsArray.forEach(item => {
                if (typeof item === 'object') {
                  // 检查常见的ID字段名
                  const possibleId = 
                    item.operational_id || 
                    item.process_id || 
                    item.gylxId || 
                    item[7]; // 从图片看可能是索引7
                  
                  if (possibleId) {
                    operationalIds.add(possibleId);
                  }
                }
              });
              
              const uniqueOpIds = Array.from(operationalIds);
              
              if (uniqueOpIds.length > 0) {
                console.log("尝试使用API获取工艺路线信息, IDs:", uniqueOpIds);
                
                // 对每个工艺路线ID单独查询
                const promises = uniqueOpIds.map(opId => {
                  return new Promise((resolve) => {
                    listOperational({ operational_id: opId }).then(response => {
                      if (response && response.rows && response.rows.length > 0) {
                        resolve(response.rows[0]);
                      } else {
                        resolve(null);
                      }
                    }).catch(() => resolve(null));
                  });
                });
                
                Promise.all(promises).then(results => {
                  const validResults = results.filter(r => r !== null);
                  
                  if (validResults.length > 0) {
                    this.processList = validResults.map(op => ({
                      operational_id: op.operational_id,
                      process_name: op.operational_name || '',
                      operational_code: op.operational_code || '',
                      operational_description: op.operational_description || '',
                      sequence: op.position || 1,
                      is_key_process: op.is_key_process || 0
                    }));
                    
                    console.log("API获取的工艺路线信息:", this.processList);
                  }
                });
              }
            }
            
            // 分离物料和工艺路线数据
            const materials = detailsArray.filter(item => item.material_id);
            
            // 设置物料列表
            this.materialList = materials.map(item => ({
              material_id: item.material_id,
              material_name: item.material_name || '',
              material_code: item.material_code || '',
              material_sfn: item.material_sfn || '',
              unit: item.material_unit || '',
              quantity: item.material_usage || 1,
              is_key_material: item.is_key_material || 0
            }));
            
          } else {
            // 处理没有明细数据的情况
            this.materialList = [];
            this.processList = [];
            console.warn("没有找到BOM明细数据");
          }
          
          this.open = true;
          this.title = "编辑BOM";
        } else {
          this.$modal.msgError("未找到BOM数据");
          console.error("未找到匹配的BOM数据:", bomResponse);
        }
      }).catch(error => {
        this.$modal.closeLoading();
        console.error("获取BOM信息失败:", error);
        this.$modal.msgError("获取BOM信息失败: " + (error.message || '未知错误'));
      });
    },
    
    /** 加载BOM详情数据 - 此方法已由直接使用Promise.all替代，但保留以兼容可能的调用 */
    loadBomDetails(bomId) {
      this.materialLoading = true;
      this.processLoading = true;
      
      // 获取基础信息
      const query = { bom_id: bomId };
      listBom(query).then(bomResponse => {
        if (bomResponse && bomResponse.rows && bomResponse.rows.length > 0) {
          const bomData = bomResponse.rows[0];
          // 设置基础表单数据
          this.form = {
            id: bomData.bom_id,
            bomCode: bomData.bom_code,
            bomVersion: bomData.bom_version,
            productName: bomData.product_name,
            productCode: bomData.product_code,
            productSpec: bomData.product_sfn,
            unit: bomData.product_unit,
            isDefault: parseInt(bomData.bom_status || '0'),
            dailyCapacity: bomData.bom_output,
            remarks: bomData.remarks
          };
          
          console.log("设置默认BOM状态:", this.form.isDefault, "原始值:", bomData.bom_status);
        }
        
        // 调用获取BOM详情的API
        return getBomDetail(bomId);
      }).then(response => {
        if (response && response.rows && Array.isArray(response.rows)) {
          // API返回的数据是数组格式，直接处理
          const detailsArray = response.rows;
          
          // 分离物料和工艺路线数据
          const materials = detailsArray.filter(item => item.material_id);
          
          // 设置物料列表
          this.materialList = materials.map(item => ({
            material_id: item.material_id,
            material_name: item.material_name || '',
            material_code: item.material_code || '',
            material_sfn: item.material_sfn || '',
            unit: item.material_unit || '',
            quantity: item.material_usage || 1,
            is_key_material: item.is_key_material || 0
          }));
          
          // 收集所有唯一的工艺路线ID
          const operationalIds = [...new Set(detailsArray
            .filter(item => item.operational_id)
            .map(item => item.operational_id))];
          
          // 如果有工艺路线ID，则获取工艺路线详情
          if (operationalIds.length > 0) {
            // 临时使用从明细中提取的信息构建工艺路线列表
            this.processList = operationalIds.map(opId => {
              const sample = detailsArray.find(item => item.operational_id === opId);
              return {
                operational_id: opId,
                process_name: `工艺路线${opId}`,
                operational_code: `GYLX${opId}`,
                operational_description: sample ? sample.operational_description || sample.process_desc || '' : '',
                sequence: 1,
                is_key_process: 0
              };
            });
          } else {
            this.processList = [];
          }
        } else {
          // 处理没有明细数据的情况
          this.materialList = [];
          this.processList = [];
          console.warn("没有找到BOM明细数据");
        }
        
        this.materialLoading = false;
        this.processLoading = false;
      }).catch((error) => {
        console.error("加载BOM详情失败:", error);
        this.materialList = [];
        this.processList = [];
        this.materialLoading = false;
        this.processLoading = false;
      });
    },
    /** 查看详情 */
    handleView(row) {
      this.$modal.loading("正在加载BOM详情...");
      
      // 正确构建查询参数，使用bom_id作为查询条件
      const query = { bom_id: row.bom_id };
      
      // 使用listBom API获取BOM详情数据
      listBom(query).then(response => {
        this.$modal.closeLoading();
        if (response && response.rows) {
          // 存储BOM详情数据到localStorage，以便详情页面获取
          localStorage.setItem('bomDetailData', JSON.stringify(response.rows));
          // 跳转到BOM详情页面
          this.$router.push({
            path: '/basic/bomDetail',
            query: { id: row.bom_id, bomCode: row.bom_code }
          });
        } else {
          this.$modal.msgError("获取BOM详情失败");
        }
      }).catch(error => {
        this.$modal.closeLoading();
        console.error("获取BOM详情失败:", error);
        this.$modal.msgError("获取BOM详情失败: " + (error.message || '未知错误'));
      });
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          // 检查BOM编号是否已获取
          if (!this.form.bomCode) {
            this.$modal.msgWarning("请先获取BOM编号");
            return;
          }
          
          // 如果是新增模式且有BOM编号，在提交前获取真正的编号
          if (!this.form.id && this.form.bomCode) {
            try {
              const response = await getAutoNumbersConsume(27);
              if (typeof response === 'string') {
                this.form.bomCode = response;
              } else if (response && response.msg) {
                this.form.bomCode = response.msg;
              }
            } catch (error) {
              this.$modal.msgError('获取最终BOM编号失败');
              return;
            }
          }
          
          // 构建完整的提交数据，包括物料和工艺路线
          const submitData = {
            ...this.form,
            // 适配后端期望的字段名称
            bom_id: this.form.id, // 确保使用表单中存储的ID
            bom_code: this.form.bomCode,
            bom_version: this.form.bomVersion,
            bom_status: this.form.isDefault,
            bom_output: this.form.dailyCapacity,
            product_id: this.form.productId, // 产品ID
            product_name: this.form.productName,
            product_code: this.form.productCode,
            product_sfn: this.form.productSpec,
            product_unit: this.form.unit,
            
            // 创建BOM明细数据
            basicBomdetails: []
          };
          
          console.log("提交的BOM ID:", submitData.bom_id, "表单原始ID:", this.form.id);

          // 如果存在工艺路线，则为每个物料关联对应的工艺路线
          if (this.processList.length > 0) {
            // 如果有工艺路线，为每个物料关联一个工艺路线
            this.materialList.forEach((material, index) => {
              // 获取对应索引的工艺路线，如果没有则使用第一个工艺路线
              const operationalIndex = index < this.processList.length ? index : 0;
              const operational = this.processList[operationalIndex];
              
              submitData.basicBomdetails.push({
                material_id: material.material_id,
                operational_id: operational ? operational.operational_id : null,
                is_key_material: material.is_key_material || 0,
                quantity: material.quantity || 1,
                is_key_process: operational ? operational.is_key_process || 0 : 0,
                sequence: operational ? operational.sequence || (operationalIndex + 1) : null
              });
            });
          } else {
            // 如果没有工艺路线，只添加物料信息
            this.materialList.forEach(material => {
              submitData.basicBomdetails.push({
                material_id: material.material_id,
                operational_id: null,
                is_key_material: material.is_key_material || 0,
                quantity: material.quantity || 1
              });
            });
          }
          
          // 确保所有工艺路线都关联到了物料
          // 检查是否有尚未关联的工艺路线
          const usedOperationalIds = submitData.basicBomdetails
            .map(item => item.operational_id)
            .filter(id => id !== null);
            
          this.processList.forEach(operational => {
            if (!usedOperationalIds.includes(operational.operational_id)) {
              // 为未关联的工艺路线创建一个关联记录，使用第一个物料或null
              const firstMaterial = this.materialList.length > 0 ? this.materialList[0] : null;
              
              submitData.basicBomdetails.push({
                material_id: firstMaterial ? firstMaterial.material_id : null,
                operational_id: operational.operational_id,
                is_key_material: firstMaterial ? firstMaterial.is_key_material || 0 : 0,
                quantity: firstMaterial ? firstMaterial.quantity || 1 : 1,
                is_key_process: operational.is_key_process || 0,
                sequence: operational.sequence || (this.processList.indexOf(operational) + 1)
              });
            }
          });
          
          console.log("提交的BOM数据:", submitData);
          
          if (this.form.id !== undefined) {
            // 更新BOM - 使用严格相等检查
            console.log("正在更新BOM，ID:", submitData.bom_id);
            updateBom(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("更新BOM失败:", error);
              this.$modal.msgError("修改失败");
            });
          } else {
            // 新增BOM
            addBom(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("新增BOM失败:", error);
              this.$modal.msgError("新增失败");
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.bom_id 
      this.$modal.confirm('是否确认删除BOM编号为"' + (row.bom_code || "") + '"的数据项?').then(function() {
        return delBom(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 表单重置
    reset() {
      // 重置基本信息表单
      this.form = {
        id: undefined,
        bomCode: "",  // 使用空字符串而不是undefined
        bomVersion: "",
        productId: "", // 产品ID
        productName: "",
        productCode: "",
        productSpec: "",
        unit: "",
        isDefault: 0,  // 确保使用数字0作为默认值
        dailyCapacity: 0,
        remarks: ""
      };
      this.resetForm("form");
      
      // 重置物料列表
      this.materialList = [];
      this.materialIds = [];
      
      // 重置工艺路线
      this.processList = [];
      
      // 重置其他状态
      this.activeTab = 'basic';
      
      // 不自动获取BOM编号，等待用户点击按钮
    },
    
    // 取消按钮
    cancelForm() {
      this.open = false;
      this.reset();
    },
    
    // ================== 产品相关方法 ==================
    
    /** 打开产品选择器 */
    openProductSelector() {
      this.productSelectVisible = true;
      this.selectedProduct = null; // 清空之前选中的产品
      this.getProductList();
    },
    
    /** 打开物料选择器 */
    openMaterialSelector() {
      this.materialSelectVisible = true;
      this.selectedMaterials = []; // 清空之前选中的物料
      this.getMaterialComponentList();
    },
    
    /** 获取产品列表 */
    getProductList() {
      this.productSelectLoading = true;
      console.log("查询产品列表，参数：", this.productQuery);
      
      // 使用listProducts1替代listProducts
      listProducts1(this.productQuery).then(response => {
        this.productSelectList = response.rows || [];
        this.productSelectTotal = response.total || 0;
        this.productSelectLoading = false;
      }).catch((error) => {
        console.error("获取产品列表失败:", error);
        this.productSelectList = [];
        this.productSelectTotal = 0;
        this.productSelectLoading = false;
      });
    },
    
    /** 获取产品列表 - 兼容旧方法名 */
    getMaterialList() {
      // 兼容旧方法名，调用新方法
      this.getProductList();
    },
    
    /** 获取物料列表 */
    getMaterialComponentList() {
      this.materialSelectLoading = true;
      console.log("查询物料列表，参数：", this.materialQuery);
      
      // 构建物料查询参数
      const query = {
        pageNum: this.materialQuery.pageNum,
        pageSize: this.materialQuery.pageSize,
        material_name: this.materialQuery.product_name, // 使用产品名称字段作为物料名称查询条件
        material_code: this.materialQuery.product_code // 使用产品编号字段作为物料编号查询条件
      };
      
      listMaterials(query).then(response => {
        // 将物料数据映射为与产品数据结构相似的格式，确保ID字段正确映射
        this.materialSelectList = (response.rows || []).map(item => ({
          product_id: item.material_id, // 将物料ID映射到product_id字段，用于后续选择
          product_name: item.material_name,
          product_code: item.material_code,
          product_sfn: item.material_sfn,
          product_unit: item.material_unit
        }));
        this.materialSelectTotal = response.total || 0;
        this.materialSelectLoading = false;
      }).catch((error) => {
        console.error("获取物料列表失败:", error);
        this.materialSelectList = [];
        this.materialSelectTotal = 0;
        this.materialSelectLoading = false;
      });
    },
    
    /** 搜索产品 */
    searchProducts() {
      console.log("执行产品搜索，搜索条件:", this.productQuery);
      this.productQuery.pageNum = 1;
      this.getProductList();
    },
    
    /** 搜索物料 */
    searchMaterials() {
      console.log("执行物料搜索，搜索条件:", this.materialQuery);
      this.materialQuery.pageNum = 1;
      this.getMaterialComponentList();
    },
    
    /** 重置产品搜索表单 */
    resetProductQuery() {
      this.productQuery = {
        pageNum: 1,
        pageSize: 10,
        product_name: undefined,
        product_code: undefined
      };
      this.getProductList();
    },
    
    /** 重置物料搜索表单 */
    resetMaterialQuery() {
      this.materialQuery = {
        pageNum: 1,
        pageSize: 10,
        product_name: undefined,
        product_code: undefined
      };
      this.getMaterialComponentList();
    },
    
    /** 处理表格选择变更 */
    handleMaterialSelectChange(selection) {
      if (this.selectorType === 'material') {
        this.selectedMaterials = selection;
        console.log("选中的物料列表:", this.selectedMaterials);
      } else if (this.selectorType === 'product' && selection.length > 0) {
        this.selectedProduct = selection[0];
        console.log("选中的产品:", this.selectedProduct);
      }
    },
    
    /** 点击产品行 */
    handleProductRowClick(row) {
      console.log("选择的产品信息:", row);
      this.selectedProduct = row;
    },
    
    /** 确认选择产品 */
    confirmSelectProduct() {
      if (this.selectedProduct) {
        // 设置表单数据
        this.form.productId = this.selectedProduct.product_id || ''; // 保存产品ID，确保这个ID是正确的
        this.form.productName = this.selectedProduct.product_name || '';
        this.form.productCode = this.selectedProduct.product_code || '';
        this.form.productSpec = this.selectedProduct.product_sfn || '';
        this.form.unit = this.selectedProduct.product_unit || '';
        this.productSelectVisible = false;
        console.log("已选择产品，ID:", this.form.productId);
      } else {
        this.$modal.msgWarning("请选择一个产品");
      }
    },
    
    /** 处理物料多选 */
    handleMaterialSelectChange(selection) {
      this.selectedMaterials = selection;
      console.log("选中的物料列表:", this.selectedMaterials);
    },
    
    /** 处理物料行点击 */
    handleMaterialRowClick(row) {
      // 物料选择时不需要特殊处理，由多选框处理
      console.log("点击物料行:", row);
    },
    
    /** 确认选择物料 */
    confirmSelectMaterial() {
      if (this.selectedMaterials.length > 0) {
        // 遍历选中的物料，添加到物料列表
        this.selectedMaterials.forEach(item => {
          // 检查是否已存在于物料列表中
          if (!this.materialList.some(existing => existing.material_id === item.product_id)) {
            // 转换产品格式为物料格式
            const materialItem = {
              material_id: item.product_id, // 保存物料ID，确保这个ID是正确的
              material_name: item.product_name,
              material_code: item.product_code,
              material_sfn: item.product_sfn,
              unit: item.product_unit,
              // 添加物料用量等信息，可根据需要设置默认值
              quantity: 1,
              is_key_material: 0
            };
            
            // 添加到物料列表
            this.materialList.push(materialItem);
            console.log("添加物料，ID:", materialItem.material_id);
          }
        });
        
        // 如果有重复项，提示用户
        if (this.selectedMaterials.some(item => 
          this.materialList.filter(existing => existing.material_id === item.product_id).length > 1
        )) {
          this.$modal.msgWarning("部分物料已存在于列表中，已跳过重复项");
        }
        
        // 关闭对话框并清空选择
        this.materialSelectVisible = false;
        this.selectedMaterials = [];
      } else {
        this.$modal.msgWarning("请至少选择一个物料");
      }
    },
    
    /** 添加物料按钮 */
    handleAddMaterial() {
      this.openMaterialSelector();
    },
    
    /** 物料选择变更 */
    handleMaterialSelectionChange(selection) {
      this.materialIds = selection.map(item => item.material_id);
    },
    
    /** 移除单个物料 */
    handleRemoveMaterial(row) {
      this.$modal.confirm('是否确认移除该物料？').then(() => {
        this.materialList = this.materialList.filter(item => item.material_id !== row.material_id);
        this.$modal.msgSuccess("移除成功");
      }).catch(() => {});
    },
    
    /** 批量移除物料 */
    handleBatchRemoveMaterial() {
      if (this.materialIds.length === 0) {
        this.$modal.msgWarning("请选择要移除的物料");
        return;
      }
      
      this.$modal.confirm('是否确认移除选中的物料？').then(() => {
        const materialIdSet = new Set(this.materialIds);
        this.materialList = this.materialList.filter(item => !materialIdSet.has(item.material_id));
        this.materialIds = [];
        this.$modal.msgSuccess("批量移除成功");
      }).catch(() => {});
    },
    
    // ================== 工艺路线相关方法 ==================
    
    /** 添加工艺路线 */
    handleAddProcess() {
      this.processForm = {
        process_id: undefined,
        process_name: undefined,
        process_desc: undefined
      };
      this.editingProcessIndex = -1;
      this.processDialogVisible = true;
    },
    
    /** 打开工艺路线选择器 */
    openOperationalSelector() {
      this.operationalSelectVisible = true;
      this.selectedOperational = null;
      this.getOperationalList();
    },
    
    /** 获取工艺路线列表 */
    getOperationalList() {
      this.operationalSelectLoading = true;
      console.log("查询工艺路线列表，参数：", this.operationalQuery);
      
      listOperational(this.operationalQuery).then(response => {
        this.operationalSelectList = response.rows || [];
        this.operationalSelectTotal = response.total || 0;
        this.operationalSelectLoading = false;
      }).catch((error) => {
        console.error("获取工艺路线列表失败:", error);
        this.operationalSelectList = [];
        this.operationalSelectTotal = 0;
        this.operationalSelectLoading = false;
      });
    },
    
    /** 搜索工艺路线 */
    searchOperational() {
      console.log("执行工艺路线搜索，搜索条件:", this.operationalQuery);
      this.operationalQuery.pageNum = 1;
      this.getOperationalList();
    },
    
    /** 重置工艺路线搜索表单 */
    resetOperationalQuery() {
      this.operationalQuery = {
        pageNum: 1,
        pageSize: 10,
        operational_name: undefined,
        operational_code: undefined
      };
      this.getOperationalList();
    },
    
    /** 处理工艺路线行点击 */
    handleOperationalRowClick(row, column, event) {
      this.selectedOperational = row;
      console.log("选中的工艺路线:", this.selectedOperational);
    },
    
    /** 确认选择工艺路线 */
    confirmSelectOperational() {
      if (this.selectedOperational) {
        // 将选中的工艺路线添加到工艺路线列表
        const processItem = {
          process_id: this.selectedOperational.operational_id || ('temp_' + new Date().getTime()),
          operational_id: this.selectedOperational.operational_id, // 保存工艺路线ID，确保这个ID是正确的
          process_name: this.selectedOperational.operational_name,
          operational_description: this.selectedOperational.operational_description,
          operational_code: this.selectedOperational.operational_code,
          // 添加工序顺序等信息
          sequence: this.processList.length + 1,
          is_key_process: 0
        };
        
        // 检查是否已存在于工艺路线列表中
        if (!this.processList.some(existing => existing.operational_id === this.selectedOperational.operational_id)) {
          this.processList.push(processItem);
          this.$modal.msgSuccess("添加工艺路线成功");
          console.log("添加工艺路线，ID:", processItem.operational_id);
        } else {
          this.$modal.msgWarning("该工艺路线已存在于列表中");
        }
      } else {
        this.$modal.msgWarning("请选择一个工艺路线");
        return;
      }
      
      // 关闭对话框并清空选择
      this.operationalSelectVisible = false;
      this.selectedOperational = null;
    },
    
    /** 编辑工艺路线 - 已移除此功能 */
    handleEditProcess(row) {
      // 此功能已移除，保留方法以避免引用错误
      console.log("工艺路线编辑功能已移除");
    },
    
    /** 移除工艺路线 */
    handleRemoveProcess(row) {
      this.$modal.confirm('是否确认移除该工艺路线？').then(() => {
        this.processList = this.processList.filter(item => item.process_id !== row.process_id);
        this.$modal.msgSuccess("移除成功");
      }).catch(() => {});
    },
    
    /** 提交工艺路线表单 */
    submitProcessForm() {
      this.$refs.processForm.validate(valid => {
        if (valid) {
          if (this.editingProcessIndex !== -1) {
            // 编辑现有工艺路线
            this.processList.splice(this.editingProcessIndex, 1, { ...this.processForm });
          } else {
            // 添加新工艺路线
            // 生成临时ID
            this.processForm.process_id = 'temp_' + new Date().getTime();
            this.processList.push({ ...this.processForm });
          }
          this.processDialogVisible = false;
          this.$modal.msgSuccess("保存成功");
        }
      });
    },
    /** 导出 */
    handleExport() {
      this.download('basic/bom/export', {
        ...this.queryParams
      }, `bom_${new Date().getTime()}.xlsx`);
    },
    /** 获取自动编号 */
    handleGetAutoNumber() {
      // 如果是编辑模式且已有BOM编号，则不重新获取
      if (this.form.id && this.form.bomCode) {
        console.log("编辑模式，保留原BOM编号:", this.form.bomCode);
        return;
      }
      
      this.$modal.loading("正在获取自动编码...");
      
      // 调用获取自动编码接口，传入编码类型参数值为27（BOM编号）
      getAutoNumbers(27).then(response => {
        this.$modal.closeLoading();
        
        console.log("自动编码API返回数据:", response);
        
        // 检查各种可能的返回格式
        if (typeof response === 'string') {
          // 直接返回字符串编号
          this.form.bomCode = response;
          return;
        }
        
        if (response === null || response === undefined) {
          this.$modal.msgError("获取自动编号失败：返回为空");
          return;
        }
        
        // 检查常见的接口返回格式
        if (response.code === 200 || response.code === 0) {
          // 标准若依框架返回格式
          if (response.data) {
            this.form.bomCode = response.data;
          } else if (response.msg && typeof response.msg === 'string') {
            this.form.bomCode = response.msg;
          } else if (response.rows && response.rows.length > 0) {
            this.form.bomCode = response.rows[0];
          } else {
            // 无法从标准字段获取，尝试直接读取
            console.warn("无法从标准返回字段获取编号，尝试直接读取response");
            this.form.bomCode = "BOM" + new Date().getTime(); // 生成临时编号
          }
        } else {
          console.error("获取自动编号失败，响应：", response);
          this.$modal.msgError("获取自动编号失败：" + (response.msg || "未知错误"));
        }
      }).catch(error => {
        this.$modal.closeLoading();
        console.error("获取自动编号失败:", error);
        this.$modal.msgError("获取自动编号失败: " + (error.message || "未知错误"));
      });
    },
    
    /** 设置BOM编号并确保响应式更新 */
    setBomCode(code) {
      // 使用Vue.set确保响应式更新
      this.$set(this.form, 'bomCode', code);
      
      // 如果上面的方法不起作用，尝试创建一个新对象来触发响应式更新
      if (!this.form.bomCode || this.form.bomCode !== code) {
        this.form = {
          ...this.form,
          bomCode: code
        };
      }
      
      // 强制更新视图
      this.$forceUpdate();
    }
  }
};
</script>

<style scoped>
.search-form {
  padding: 15px;
  background: #fff;
  border-radius: 5px;
  margin-bottom: 20px;
}

.title-container {
  margin-bottom: 15px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

.mb8 {
  margin-bottom: 8px;
}

.blue-text {
  color: #409EFF;
}

.red-text {
  color: #F56C6C;
}

.link-type {
  color: #409EFF;
  cursor: pointer;
}

.link-type:hover {
  text-decoration: underline;
}
.material-container,
.process-container {
  margin-top: 10px;
  min-height: 300px;
}

.material-header,
.process-header {
  margin-bottom: 15px;
}

.process-header .el-button {
  margin-bottom: 10px;
}

.empty-data,
.empty-process {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 250px;
  color: #909399;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 15px;
  color: #dcdfe6;
}

.empty-text {
  font-size: 14px;
  margin-bottom: 20px;
}

.el-row {
  margin-bottom: 15px;
}

.blue-text {
  color: #409EFF;
}

.red-text {
  color: #F56C6C;
}

.el-tabs {
  min-height: 380px;
}

.bom-code-input .el-input__inner {
  color: #606266 !important;
  background-color: #f5f7fa !important;
}
</style>